const schema = require("../dao/userSchema");
const token = require("./token");
/**
 *
 加密
 *
 @method hex
 *
 @param {String} pwd 密码
 */

function hex(pwd) {
    const crypto = require("crypto");
    const sha1 = crypto.createHash("sha1");
    sha1.update(pwd);
    return sha1.digest("hex");
}
/**
 *
 新增用户
 *
 @method addUser
 *
 @param {String} account 账号
 @param {String} pwd 密码
 @param {Function} cb 密码 
 */
function addUser(account, pwd, name, avatar, cb) {
    let hexPwd = hex(pwd);
    let user = new schema({
        account: account,
        password: hexPwd,
        name: name,
        avatar: avatar
    });
    schema.find({ account: account }, (err, res) => {
        if (err) {
            console.log(err);
            cb({ message: "添加用户失败！", ok: false });
        } else {
            if (res.length === 0) {
                let promise = user.save();
                promise
                    .then(doc => {
                        cb({ message: "添加用户成功", ok: true, data: doc });
                    })
                    .catch(er => {
                        console.log(er);
                    });
            } else {
                cb({ message: "账号已存在，添加用户失败！", ok: false });
            }
        }
    });
}

function findUserById(id, cb) {
    schema.findById(id, (err, res) => {
        if (err) cb({ message: "查找用户失败！", ok: false });
        cb({ message: "查找用户成功", ok: true, data: res });
    });
}

function getAllUsers(cb) {
    schema.find((err, res) => {
        if (err) cb({ message: "获取所有用户失败！", ok: false });
        cb({ message: "获取所有用户成功", ok: true, data: res });
    });
}

function login(account, pwd, cb) {
    schema.findOne({ account: account, password: hex(pwd) }, (err, res) => {
        if (err) cb({ message: "登录失败！", ok: false });
        else {
            if (res === null) cb({ message: "账号或密码不正确", ok: false });
            else {
                let new_token = token.createToken(res, 10 * 60 * 60 * 24 * 30);
                // 10 * 60 * 60 * 24 * 30
                global.tokenMap.set(account, new_token);
                cb({
                    message: "登录成功",
                    ok: true,
                    data: res,
                    token: new_token
                });
            }
        }
    });
}

function testToken(account, sign, cb) {
    console.log(account + "的token有效：" + token.checkToken(sign));
    cb({ message: "测试成功", ok: token.checkToken(sign) });
}

module.exports = {
    findById: findUserById,
    add: addUser,
    login: login,
    test: testToken,
    getAll: getAllUsers
};
